package fast.main.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Super {
	public static Map<String, String> sqlMap=new HashMap<String, String>();
	static{
		try {
			for (File tempFile : new File(Super.class.getClassLoader().getResource("/conf/sql/").getPath()).listFiles()) {
				System.out.println(tempFile.getName());
				if(!(tempFile.isFile()&&tempFile.getName().matches("^jdbc-.*\\.xml$"))) continue;
				//获取根节点
				Element xmldoc= DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(tempFile).getDocumentElement();
				//获取子节点
				NodeList childs=xmldoc.getElementsByTagName("SqlStatement");
				//加载子节点
				for (int i = 0; i < childs.getLength(); i++) {
					Element tempNode=(Element) childs.item(i);
					String attrName=tempNode.getAttribute("key");
					String content=tempNode.getTextContent();
					sqlMap.put(attrName, content);
					System.out.println(">>>>>>>>>>>>>>>>>>JDBC文件："+tempFile.getName()+",加载["+childs.getLength()+"]条数据<<<<<<<<<<<<<<<");
				}
			}
		} catch (SAXException e) {
			System.out.println("Super超类异常："+e.getLocalizedMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Super超类异常："+e.getLocalizedMessage());
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			System.out.println("Super超类异常："+e.getLocalizedMessage());
			e.printStackTrace();
		}
	}


	public static String getSql(String exeSql,Object... par){
		if(par.length==1&&Object[].class.isAssignableFrom(par[0].getClass())) par=(Object[])par[0];
		//忽略空参数模式
		StringBuilder sql=new StringBuilder(exeSql);
		List<Object> param=new ArrayList<Object>();
		int step=0;
		while (true) {
			int temp1=sql.indexOf("(-",step);
			int temp2=temp1==-1?-1:sql.indexOf("-)",temp1);
			if(temp1==-1||temp2==-1) break;
			step=temp2+2;
			sql.replace(temp1,step, "(1=? or "+sql.substring(temp1+2,temp2)+")");
		}
		step=0;
		for (int i = 0; i < par.length; ++i) {
			step=sql.indexOf("?",step)+1;
			if(step!=0&&"1=? or ".equals(sql.substring(step-3<sql.length()?(step-3):sql.length()-1,step+4<sql.length()?(step+4):sql.length()))){
				if(par[i]==null||(par[i] instanceof String && "".equals(par[i]))) param.add("1"); else param.add("0");
				i--;
			}else{
				param.add(par[i]);
			}
		}
		for (int i = 0; i < param.size(); i++) {
			int idx=sql.indexOf("?");
			sql.replace(idx,idx+1 , "'"+String.valueOf(param.get(i)+"'"));
		}
		System.out.println(">>>>>>sql:"+sql.toString());
		return sql.toString();
	}


	


}
